<template>
    <view @longtap.stop="longtap">
		<canvas :canvas-id="item.id" :id="item.id" :style="{width:width,height: height}" v-for="(item,index) in listCode" :key="item.id" />
	</view>
</template>
<script>
	import { BarCode,GetCodeImg } from '../../js_sdk';
	import { getUUid, deepClone } from '../../common/helper.js'
	export default {
		name: 'WBarcode',
		props:{
			options:{
				type: Object,
				required: true,
				default: () =>{
					return {
						
					}
				}
			}
		},
		data () {
			return {
				listCode: [],
				id: getUUid(),
				height: null,
				width: null,
			}
		},
		created() {
			this.height = this.options.height + 'rpx';
			this.width = this.options.width + 'rpx';
			this.SpecialTreatment(this.options)
			this.$nextTick(()=>{
				this.generateCode();
			})
		},
		watch: {
			options:{
				deep: true,
				handler (val) {
					this.height = val.height + 'rpx';
					this.width = val.width + 'rpx';
					this.SpecialTreatment(val)
					setTimeout(()=>{// h5平台动态改变canvas大小
						this.generateCode();
					},50)
				}
			}
		},
		methods: {
			longtap (e){
				this.$emit('longtap',e)
			},
			SpecialTreatment (val) {//微信小程序渲染多个canvas特殊处理
					let obj = deepClone(val);
					obj.id = this.id;
					this.listCode = [obj]
			},
			generateCode () {
				try{
					const parameter = {...this.options,id: this.id,ctx: this};
					BarCode(parameter,(res)=>{
						this.$emit('generate',res)
					})
				}catch(err){}
			},
			async GetCodeImg (){
				try{
					return await GetCodeImg({id: this.id,width: this.options.width,height: this.options.height,ctx: this});
				}catch(e){}
			}
		}
	}
</script>